#include <vector>

using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int a)
        : val(a), left(nullptr), right(nullptr)
    {
    }
};

class Solution
{
public:
    TreeNode *Create(vector<int> &inorder, vector<int> &postorder, int &root, int begin, int end)
    {
        if (begin > end)
        {
            return nullptr;
        }

        TreeNode *_root = new TreeNode(postorder[root]);
        root--;

        int inpos = begin;
        while (inpos < end)
        {
            if (inorder[inpos] == _root->val)
            {
                break;
            }
            inpos++;
        }

        _root->right = Create(inorder, postorder, root, inpos + 1, end);
        _root->left = Create(inorder, postorder, root, begin, inpos - 1);

        return _root;
    }
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
    {
        int root = inorder.size() - 1;
        return Create(inorder, postorder, root, 0, inorder.size() - 1);
    }
};